<!DOCTYPE html>
<html>
  <head><meta name="generator" content="Hexo 3.8.0">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="fengzhaoyang&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
  <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
    CopyOnWriteArrayList 与 Collections synchronizedList 的性能对比 | fzy-blog
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/css/style.css">
  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
  <script src="/js/qrious.js"></script>
  
  
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.png">
</div>
  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>fzy-blog</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">Tags</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">Archives</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/project/" class="item-link">Projects</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">About</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">Tags</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">Archives</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/project/" class="menu-link">Projects</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">About</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>CopyOnWriteArrayList 与 Collections synchronizedList 的性能对比</h2>
  <p class="post-date">2019-05-24</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="CopyOnWriteArrayList-与-Collections-synchronizedList-的性能对比"><a href="#CopyOnWriteArrayList-与-Collections-synchronizedList-的性能对比" class="headerlink" title="CopyOnWriteArrayList 与 Collections synchronizedList 的性能对比"></a>CopyOnWriteArrayList 与 Collections synchronizedList 的性能对比</h1><p>列表实现有 ArrayList、Vector、CopyOnWriteArrayList、Collections.synchronizedList(list)四种方式。<br>1 ArrayList<br>ArrayList 是非线性安全，此类的 iterator 和 listIterator 方法返回的迭代器是快速失败的：在创建迭代器之后，除非通过迭代器自身的 remove 或 add 方法从结构上对列表进行修改，否则在任何时间以任何方式对列表进行修改，迭代器都会抛出 ConcurrentModificationException。即在一方在便利列表，而另一方在修改列表时，会报 ConcurrentModificationException 错误。而这不是唯一的并发时容易发生的错误，在多线程进行插入操作时，由于没有进行同步操作，容易丢失数据。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">ensureCapacity(size + <span class="number">1</span>);  <span class="comment">// Increments modCount!!</span></span><br><span class="line">elementData[size++] = e;<span class="comment">//使用了size++操作，会产生多线程数据丢失问题。</span></span><br><span class="line"><span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>因此，在开发过程当中，ArrayList 并不适用于多线程的操作。<br>2 Vector<br>从 JDK1.0 开始，Vector 便存在 JDK 中，Vector 是一个线程安全的列表，采用数组实现。其线程安全的实现方式是对所有操作都加上了 synchronized 关键字，这种方式严重影响效率，因此，不再推荐使用 Vector 了，Stackoverflow 当中有这样的描述：Why is Java Vector class considered obsolete or deprecated?。<br>3 Collections.synchronizedList &amp; CopyOnWriteArrayList<br>CopyOnWriteArrayList 和 Collections.synchronizedList 是实现线程安全的列表的两种方式。两种实现方式分别针对不同情况有不同的性能表现，其中 CopyOnWriteArrayList 的写操作性能较差，而多线程的读操作性能较好。而 Collections.synchronizedList 的写操作性能比 CopyOnWriteArrayList 在多线程操作的情况下要好很多，而读操作因为是采用了 synchronized 关键字的方式，其读操作性能并不如 CopyOnWriteArrayList。因此在不同的应用场景下，应该选择不同的多线程安全实现类。<br>3.1 Collections.synchronizedList<br>Collections.synchronizedList 的源码可知，其实现线程安全的方式是建立了 list 的包装类，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">List&lt;T&gt; <span class="title">synchronizedList</span><span class="params">(List&lt;T&gt; list)</span> </span>&#123;</span><br><span class="line"><span class="keyword">return</span> (list <span class="keyword">instanceof</span> RandomAccess ?</span><br><span class="line">               <span class="keyword">new</span> SynchronizedRandomAccessList&lt;T&gt;(list) :</span><br><span class="line">               <span class="keyword">new</span> SynchronizedList&lt;T&gt;(list));<span class="comment">//根据不同的list类型最终实现不同的包装类。</span></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>其中，SynchronizedList 对部分操作加上了 synchronized 关键字以保证线程安全。但其 iterator()操作还不是线程安全的。部分 SynchronizedList 的代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">get</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span>(mutex) &#123;<span class="keyword">return</span> list.get(index);&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> E <span class="title">set</span><span class="params">(<span class="keyword">int</span> index, E element)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span>(mutex) &#123;<span class="keyword">return</span> list.set(index, element);&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> index, E element)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span>(mutex) &#123;list.add(index, element);&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ListIterator&lt;E&gt; <span class="title">listIterator</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> list.listIterator(); <span class="comment">// Must be manually synched by user 需要用户保证同步，否则仍然可能抛出ConcurrentModificationException</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ListIterator&lt;E&gt; <span class="title">listIterator</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> list.listIterator(index); <span class="comment">// Must be manually synched by user &lt;span style="font-family: Arial, Helvetica, sans-serif;"&gt;需要用户保证同步，否则仍然可能抛出ConcurrentModificationException&lt;/span&gt;</span></span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<p>3.2 CopyOnWriteArrayList<br>从字面可以知道，CopyOnWriteArrayList 在线程对其进行些操作的时候，会拷贝一个新的数组以存放新的字段。其写操作的代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** The lock protecting all mutators */</span></span><br><span class="line">    <span class="keyword">transient</span> <span class="keyword">final</span> ReentrantLock lock = <span class="keyword">new</span> ReentrantLock();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** The array, accessed only via getArray/setArray. */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">transient</span> Object[] array;<span class="comment">//保证了线程的可见性</span></span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> ReentrantLock lock = <span class="keyword">this</span>.lock;<span class="comment">//ReentrantLock 保证了线程的可见性和顺序性，即保证了多线程安全。</span></span><br><span class="line">    lock.lock();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Object[] elements = getArray();</span><br><span class="line">        <span class="keyword">int</span> len = elements.length;</span><br><span class="line">        Object[] newElements = Arrays.copyOf(elements, len + <span class="number">1</span>);<span class="comment">//在原先数组基础之上新建长度＋1的数组，并将原先数组当中的内容拷贝到新数组当中。</span></span><br><span class="line">        newElements[len] = e;<span class="comment">//设值</span></span><br><span class="line">        setArray(newElements);<span class="comment">//对新数组进行赋值</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        lock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>其读操作代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">get</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">       <span class="keyword">return</span> (E)(getArray()[index]);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<pre><code>其没有加任何同步关键字，根据以上写操作的代码可知，其每次写操作都会进行一次数组复制操作，然后对新复制的数组进行些操作，不可能存在在同时又读写操作在同一个数组上（不是同一个对象），而读操作并没有对数组修改，不会产生线程安全问题。Java中两个不同的引用指向同一个对象，当第一个引用指向另外一个对象时，第二个引用还将保持原来的对象。
其中setArray()操作仅仅是对array进行引用赋值。Java中“=”操作只是将引用和某个对象关联，假如同时有一个线程将引用指向另外一个对象，一个线程获取这个引用指向的对象，那么他们之间不会发生ConcurrentModificationException，他们是在虚拟机层面阻塞的，而且速度非常快，是一个原子操作，几乎不需要CPU时间。

在列表有更新时直接将原有的列表复制一份，并再新的列表上进行更新操作，完成后再将引用移到新的列表上。旧列表如果仍在使用中(比如遍历)则继续有效。如此一来就不会出现修改了正在使用的对象的情况(读和写分别发生在两个对象上)，同时读操作也不必等待写操作的完成，免去了锁的使用加快了读取速度。
</code></pre><p>3.3 Collections.synchronizedList &amp; CopyOnWriteArrayList 在读写操作上的差距<br>测试代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.yang.test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.*;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created with IntelliJ IDEA.</span></span><br><span class="line"><span class="comment"> * User: yangzl2008</span></span><br><span class="line"><span class="comment"> * Date: 14-9-18</span></span><br><span class="line"><span class="comment"> * Time: 下午8:36</span></span><br><span class="line"><span class="comment"> * To change this template use File | Settings | File Templates.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test02</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> NUM = <span class="number">10000</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> THREAD_COUNT = <span class="number">16</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testAdd</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list1 = <span class="keyword">new</span> CopyOnWriteArrayList&lt;Integer&gt;();</span><br><span class="line">        List&lt;Integer&gt; list2 = Collections.synchronizedList(<span class="keyword">new</span> ArrayList&lt;Integer&gt;());</span><br><span class="line">        Vector&lt;Integer&gt; v  = <span class="keyword">new</span> Vector&lt;Integer&gt;();</span><br><span class="line"></span><br><span class="line">        CountDownLatch add_countDownLatch = <span class="keyword">new</span> CountDownLatch(THREAD_COUNT);</span><br><span class="line">        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> add_copyCostTime = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> add_synchCostTime = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; THREAD_COUNT; i++) &#123;</span><br><span class="line">            add_copyCostTime += executor.submit(<span class="keyword">new</span> AddTestTask(list1, add_countDownLatch)).get();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"CopyOnWriteArrayList add method cost time is "</span> + add_copyCostTime);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; THREAD_COUNT; i++) &#123;</span><br><span class="line">            add_synchCostTime += executor.submit(<span class="keyword">new</span> AddTestTask(list2, add_countDownLatch)).get();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"Collections.synchronizedList add method cost time is "</span> + add_synchCostTime);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testGet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list = initList();</span><br><span class="line"></span><br><span class="line">        List&lt;Integer&gt; list1 = <span class="keyword">new</span> CopyOnWriteArrayList&lt;Integer&gt;(list);</span><br><span class="line">        List&lt;Integer&gt; list2 = Collections.synchronizedList(list);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> get_copyCostTime = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> get_synchCostTime = <span class="number">0</span>;</span><br><span class="line">        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);</span><br><span class="line">        CountDownLatch get_countDownLatch = <span class="keyword">new</span> CountDownLatch(THREAD_COUNT);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; THREAD_COUNT; i++) &#123;</span><br><span class="line">            get_copyCostTime += executor.submit(<span class="keyword">new</span> GetTestTask(list1, get_countDownLatch)).get();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"CopyOnWriteArrayList add method cost time is "</span> + get_copyCostTime);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; THREAD_COUNT; i++) &#123;</span><br><span class="line">            get_synchCostTime += executor.submit(<span class="keyword">new</span> GetTestTask(list2, get_countDownLatch)).get();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"Collections.synchronizedList add method cost time is "</span> + get_synchCostTime);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> List&lt;Integer&gt; <span class="title">initList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list = <span class="keyword">new</span> ArrayList&lt;Integer&gt;();</span><br><span class="line">        <span class="keyword">int</span> num = <span class="keyword">new</span> Random().nextInt(<span class="number">1000</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; NUM; i++) &#123;</span><br><span class="line">            list.add(num);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">AddTestTask</span> <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">Integer</span>&gt; </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list;</span><br><span class="line">        CountDownLatch countDownLatch;</span><br><span class="line"></span><br><span class="line">        AddTestTask(List&lt;Integer&gt; list, CountDownLatch countDownLatch) &#123;</span><br><span class="line">            <span class="keyword">this</span>.list = list;</span><br><span class="line">            <span class="keyword">this</span>.countDownLatch = countDownLatch;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            <span class="keyword">int</span> num = <span class="keyword">new</span> Random().nextInt(<span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; NUM; i++) &#123;</span><br><span class="line">                list.add(num);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">            countDownLatch.countDown();</span><br><span class="line">            <span class="keyword">return</span> (<span class="keyword">int</span>) (end - start);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">GetTestTask</span> <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">Integer</span>&gt; </span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list;</span><br><span class="line">        CountDownLatch countDownLatch;</span><br><span class="line"></span><br><span class="line">        GetTestTask(List&lt;Integer&gt; list, CountDownLatch countDownLatch) &#123;</span><br><span class="line">            <span class="keyword">this</span>.list = list;</span><br><span class="line">            <span class="keyword">this</span>.countDownLatch = countDownLatch;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            <span class="keyword">int</span> pos = <span class="keyword">new</span> Random().nextInt(NUM);</span><br><span class="line">            <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; NUM; i++) &#123;</span><br><span class="line">                list.get(pos);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">            countDownLatch.countDown();</span><br><span class="line">            <span class="keyword">return</span> (<span class="keyword">int</span>) (end - start);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>操作结果：<br>| | CopyOnWriteArrayList | Collections.synchronizedList| CopyOnWriteArrayList|Collections.synchronizedList |<br>| :——|:——|:——|:——|:——|<br>| 1 | 567 | 2 | 1 | 1|<br>|2 |567 |2 |1 |1<br>|4 |3088 |3 |2 |2<br>|8 |25975 |28 |2 |3<br>|16 |295936 |44 |2 |6<br>|32 |－ |－ |3 |8<br>|64 |－ |－ |7 |21<br>|128 |－ |－ |9 |38</p>
<pre><code>写操作：在线程数目增加时CopyOnWriteArrayList的写操作性能下降非常严重，而Collections.synchronizedList虽然有性能的降低，但下降并不明显。
读操作：在多线程进行读时，Collections.synchronizedList和CopyOnWriteArrayList均有性能的降低，但是Collections.synchronizedList的性能降低更加显著。
</code></pre><p>4 结论<br>CopyOnWriteArrayList，发生修改时候做 copy，新老版本分离，保证读的高性能，适用于以读为主，读操作远远大于写操作的场景中使用，比如缓存。而 Collections.synchronizedList 则可以用在 CopyOnWriteArrayList 不适用，但是有需要同步列表的地方，读写操作都比较均匀的地方。</p>
<p>来源： <a href="http://blog.csdn.net/zljjava/article/details/48139465" target="_blank" rel="noopener">http://blog.csdn.net/zljjava/article/details/48139465</a></p>
</section>
    <!-- Tags START -->
    
    <div class="tags">
      <span>Tags:</span>
      
  <a href="/tags#多线程异步并发">
    <span class="tag-code">多线程异步并发</span>
  </a>

    </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2019/05/24/多线程异步并发/Java多线程总结之线程安全队列Queue/">
        <span class="nav-arrow">← </span>
        
          Java多线程总结之线程安全队列Queue
        
      </a>
    
    
      <a class="nav-right" href="/2019/05/24/多线程异步并发/Java8新的异步编程方式CompletableFuture/">
        
          Java8 新的异步编程方式 CompletableFuture
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
    <div class="money-like">
      <div class="reward-btn">
        赏
        <span class="money-code">
          <span class="alipay-code">
            <div class="code-image"></div>
            <b>使用支付宝打赏</b>
          </span>
          <span class="wechat-code">
            <div class="code-image"></div>
            <b>使用微信打赏</b>
          </span>
        </span>
      </div>
      <p class="notice">若你觉得我的文章对你有帮助，欢迎点击上方按钮对我打赏</p>
    </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
    <div class="qrcode">
      <canvas id="share-qrcode"></canvas>
      <p class="notice">扫描二维码，分享此文章</p>
    </div>
    
    <!-- 二维码 END -->
    
    <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
  <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#CopyOnWriteArrayList-与-Collections-synchronizedList-的性能对比"><span class="toc-nav-text">CopyOnWriteArrayList 与 Collections synchronizedList 的性能对比</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'https://fengzhaoy.github.io/2019/05/24/多线程异步并发/CopyOnWriteArrayList与CollectionssynchronizedList的性能对比/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function () {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function () {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="' + src +
          '" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function () {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


<script>
  var qr = new QRious({
    element: document.getElementById('share-qrcode'),
    value: document.location.href
  });
</script>





    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2019
  </p>
</footer>

<script>
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async ("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function () {
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async ("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function () {
    $('figure pre').each(function (i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/js/script.js"></script>
  </body>
</html>